<template>
    <el-date-picker v-model="dataCache.datetime" :size="size"
                    :type="type" :align="align" :clearable="clearable" @change="filterChange"
                    :picker-options="pickerOptions" :placeholder="$t('form.datetime.placeholder')">
    </el-date-picker>
</template>

<script>
export default {
    name: "PageOptionDatetime",
    model: {
        prop: 'datetime',
        event: 'change'
    },
    props: {
        type: {
            type: String,
            required: true
        },
        size: {
            type: String,
            default: null
        },
        align: {
            type: String,
            default: 'left'
        },
        datetime: {
            type: Number,
            default: null
        },
        clearable: {
            type: Boolean,
            default: true
        },
        initLastDay: {
            type: Number,
            default: null
        },
        initLastDayEvent: {
            type: Boolean,
            default: true
        },
        disabledTodayBefore: {
            type: Boolean,
            default: false
        },
        disabledTodayAfter: {
            type: Boolean,
            default: false
        },
    },
    data() {
        return {
            dataCache: {
                datetime: null,
            },
        }
    },
    computed: {
        // 时间选择器参数
        pickerOptions: function () {
            return {
                disabledDate: (time) => {
                    if (this.disabledTodayBefore) {
                        return time.getTime() < Date.now() - 86400000;
                    }
                    if (this.disabledTodayAfter) {
                        return time.getTime() > Date.now();
                    }
                }
            };
        }
    },
    created() {
        // 初始化选中最近 n 天
        if (this.initLastDay != null && this.initLastDay >= 0) {
            this.dataCache.datetime = new Date(this.$store.getters['config/timedDayTimestamp']() * 1000 - 1000 * 3600 * 24 * this.initLastDay);
            // 初始化时触发 change 事件
            if (this.initLastDayEvent) {
                this.filterChange(this.dataCache.datetime);
            }
        }
    },
    watch: {
        // 外部改变数据
        datetime: {
            immediate: true,
            handler: function (n, o) {
                if (n != o) {
                    this.dataCache.datetime = _.isNull(n) ? null : new Date(n * 1000);
                }
            }
        }
    },
    methods: {
        // 点击选中数据
        filterChange(datetime) {
            let datetimeCache = _.cloneDeep(datetime);
            if (!_.isNull(datetimeCache)) {
                datetimeCache = this.$store.getters['config/filterDatetimeToTimestamp'](datetimeCache);
            }
            // 对外广播事件
            this.$emit('change', datetimeCache);
        },
    },
}
</script>

<style scoped>

</style>
